﻿using System;
using System.IO;
using System.Net;
using Aliyun.OSS;
using Aliyun.OSS.Common;
using QQ2564874169.Core.Filespace;

namespace QQ2564874169.File.Oss
{
    public class OssFile : IFile
    {
        private OssClient _oss;
        private string _bucket;
        private string _domain;
        private string _endpoint;

        public OssFile(string bucket, string endpoint, string key, string secret, string domain = null)
        {
            _bucket = bucket;
            _domain = domain;
            _endpoint = endpoint;
            _oss = new OssClient(_endpoint, key, secret);
        }

        private static string SetPath(string path)
        {
            return path.Replace("\\", "/").Trim('/').ToLower();
        }

        public void Create(string path, Stream file)
        {
            if (path == null)
                throw new ArgumentNullException(nameof(path));
            path = SetPath(path);
            if (path.EndsWith("/"))
                throw new NotSupportedException("结尾字符不能是'/'");
            file.Position = 0;
            var code = _oss.PutObject(_bucket, path, file).HttpStatusCode;
            if (code != HttpStatusCode.OK)
            {
                throw new OssException("创建失败：HTTPCODE=" + code);
            }
        }

        public bool ExistsFile(string path)
        {
            if (path == null)
                return false;
            return _oss.DoesObjectExist(_bucket, SetPath(path));
        }

        public void RemoveFile(string path)
        {
            if (path == null)
                return;
            _oss.DeleteObject(_bucket, SetPath(path));
        }

        public string GetUri(string path)
        {
            if (path == null)
                return null;
            path = SetPath(path);
            if (string.IsNullOrEmpty(_domain))
                return "http://" + _bucket + "." + _endpoint + "/" + path;
            return _domain + "/" + path;
        }

        public Stream GetFile(string path)
        {
            if (path == null)
                return null;
            return _oss.GetObject(_bucket, SetPath(path)).Content;
        }
    }
}
